﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Catering_Rules;
using System.Web.Services;
using System.Collections;
using System.Text;

namespace Catering.Catering_Page.Caipin
{
    public partial class Caipu_Manage : UserIsNull
    {
        View_Operaction_Common voc = new View_Operaction_Common();
        public static string strLibrary = string.Empty;
        public int m_CaipuNum = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetTableHtml();
                this.LoadData();
                this.Tv_Dish.CollapseAll();
            }
        }

        //删除菜
        protected void img_btn_Click(object sender, ImageClickEventArgs e)
        {
            if (this.Tv_Dish.SelectedNode == null || this.Tv_Dish.SelectedNode.Target == "type")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择菜节点！');</script>");
                return;
            }

            string strid = this.Tv_Dish.SelectedNode.Value;
            if (new Catering_Rules.library_Dish().Delete(Convert.ToInt32(strid)))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('删除成功!');window.location='Caipu_Manage.aspx?Lid=" + this.butLibaryID.Value + "';</script>");
            }

        }

        //修改菜信息
        protected void Btn_Cai_Edit_Click(object sender, ImageClickEventArgs e)
        {
            if (this.Tv_Dish.SelectedNode == null || this.Tv_Dish.SelectedNode.Target == "type")
            {
                return;
            }

            Catering_Model.E_Dish md = new Catering_Model.E_Dish();
            md.id = Convert.ToInt32(this.Tv_Dish.SelectedValue);
            md.Name = this.Txt_caipin.Text.Trim();
            md.Characteristic = this.txt_tedian.Text.Trim();
            md.Method = this.Txt_zuofa.Text.Trim();
            md.Picture = this.ImgCaipin.ImageUrl;
            md.FMID = Convert.ToInt32(this.Txt_FMID.Text);
            md.DTID = Convert.ToInt32(this.Txt_DTID.Text);
            new Catering_Rules.T_Dish().Update(md);
            Response.Redirect("Caipu_Manage.aspx");
        }

        //上传图片
        protected void butUpClose_Click(object sender, EventArgs e)
        {
            this.ImgCaipin.ImageUrl = new View_Operaction.Caipin_Manage_Operaction().UpImage(this.File_Upload);
        }

        //根据菜谱库绑定菜
        public void LoadData()
        {
            dt_DishType = new Catering_Rules.DishType().GetAllList(false).Tables[0];
            this.Drop_DishType.Items.Clear();
            DataRow[] RowList = dt_DishType.Select("ParentID=0");
            this.LoadDrop(RowList);

            if (Request.QueryString["Lid"] != null)
            {
                Catering_Model.library md_library = new Catering_Rules.library().GetModel(Convert.ToInt32(Request.QueryString["Lid"].ToString()));
                this.butLibaryID.Value = md_library.id.ToString();
                this.Loadlibrary_Dish(md_library.id.ToString());
                this.lab_Library_Name.Text = md_library.LName + "（" + m_CaipuNum + "）";
            }
            else
            {
                DataTable dt_Library = new Catering_Rules.library().GetAllList().Tables[0];
                if (dt_Library != null && dt_Library.Rows.Count > 0)
                {
                    this.butLibaryID.Value = dt_Library.Rows[0]["id"].ToString();
                    this.Loadlibrary_Dish(dt_Library.Rows[0]["id"].ToString());
                    this.lab_Library_Name.Text = dt_Library.Rows[0]["LName"].ToString() + "（" + m_CaipuNum + "）";
                }
            }
        }

        //绑定菜品分类
        private void LoadDrop(DataRow[] RowList)
        {
            foreach (DataRow row in RowList)
            {
                ListItem ite = new ListItem();
                string Temp = "";
                int Level = Convert.ToInt32(row["TypeLevel"].ToString());
                if (Level > 0)
                {
                    for (int i = 0; i < Level; i++)
                    {
                        Temp += "┣";
                    }
                }
                ite.Text = Temp + row["DT"].ToString();
                ite.Value = row["id"].ToString();
                this.Drop_DishType.Items.Add(ite);
                DataRow[] TempList = dt_DishType.Select("ParentID=" + row["id"].ToString());
                if (TempList != null && TempList.Count() > 0)
                {
                    this.LoadDrop(TempList);
                }
            }
        }

        //选择菜谱库
        protected void ButLibrary_Click(object sender, EventArgs e)
        {
            Catering_Model.library md_library = new Catering_Rules.library().GetModel(Convert.ToInt32(Convert.ToInt32(this.butLibaryID.Value)));
            this.Loadlibrary_Dish(md_library.id.ToString());
            this.lab_Library_Name.Text = md_library.LName + "（" + m_CaipuNum + "）";
        }

        private DataTable dt_DishType = new DataTable();        //菜品分类
        private DataTable dt_library_Dish = new DataTable();    //菜谱菜品关系
        private DataTable dt_Dish = new DataTable();            //菜品
        #region 根据菜谱ID 加载对应的菜谱树
        /// <summary>
        /// 加载菜谱库菜类数据
        /// </summary>
        /// <param name="LibraryId">菜谱ID</param>
        public void Loadlibrary_Dish(string LibraryId)
        {
            this.Tv_Dish.Nodes.Clear();
            dt_DishType = new Catering_Rules.DishType().GetAllList(false).Tables[0];
            dt_library_Dish = new Catering_Rules.library_Dish().GetList("libraryID=" + LibraryId).Tables[0];
            dt_Dish = new Catering_Rules.T_Dish().GetList("").Tables[0]; //区域测试屏蔽 AreaIDS like '%," + LoginPersonnel.AreaID + ",%'

            DataRow[] TypeList = dt_DishType.Select("ParentID=0");
            foreach (DataRow row in TypeList)
            {
                TreeNode tn = new TreeNode();
                tn.Text = row["DT"].ToString();
                tn.Value = row["id"].ToString();
                tn.Target = "type";
                this.LoadDishType(tn, row["id"].ToString());
                this.LoadDish(tn, row["id"].ToString());
                this.Tv_Dish.Nodes.Add(tn);
            }
        }

        /// <summary>
        /// 加载菜谱分类
        /// </summary>
        /// <param name="tv">父节点</param>
        /// <param name="TypeID">父节点类别ID</param>
        private void LoadDishType(TreeNode tv, string TypeID)
        {
            DataRow[] TypeList = dt_DishType.Select("ParentID="+TypeID);
            foreach (DataRow row in TypeList)
            {
                TreeNode tn = new TreeNode();
                tn.Text = row["DT"].ToString();
                tn.Value = row["id"].ToString();
                tn.Target = "type";
                this.LoadDishType(tn, row["id"].ToString());
                this.LoadDish(tn, row["id"].ToString());
                tv.ChildNodes.Add(tn);
            }
        }

        /// <summary>
        /// 加载菜品
        /// </summary>
        /// <param name="tv">父节点</param>
        /// <param name="TypeID">菜品分类ID</param>
        private void LoadDish(TreeNode tv, string TypeID)
        {
            DataRow[] DishList = dt_Dish.Select("DTID="+TypeID);
            for (int i = 0; i < DishList.Length; i++)
            {
                if (dt_library_Dish.Select("DishID=" + DishList[i]["id"].ToString()).Count() > 0)
                {
                    TreeNode tn = new TreeNode();
                    tn.Text = DishList[i]["Name"].ToString();
                    tn.Value = DishList[i]["id"].ToString();
                    tn.Target = "item";
                    tv.ChildNodes.Add(tn);
                    m_CaipuNum++;
                }
            }
        }
        #endregion

        //添加菜品至菜谱库
        [WebMethod]
        public static string Addlibrary_Dish(string libraryID, string stridList)
        {
            string[] s_DishList = stridList.TrimEnd(',').Split(',');
            foreach (string str in s_DishList)
            {
                string DishId = str.Split('|')[0];
                string DishTypeId = str.Split('|')[1];
                Catering_Model.library_Dish md_library_Dish = new Catering_Model.library_Dish();
                md_library_Dish.DishID = Convert.ToInt32(DishId);
                md_library_Dish.DishTypeID = Convert.ToInt32(DishTypeId);
                md_library_Dish.libraryID = Convert.ToInt32(libraryID);
                new Catering_Rules.library_Dish().Add(md_library_Dish);
            }
            return "OK";
        }

        //获取菜信息
        [WebMethod]
        public static ArrayList GetDishById(string DishID)
        {
            string strid = DishID.Split('|')[0];
            ArrayList al = new ArrayList();
            Catering_Model.E_Dish md = new Catering_Rules.T_Dish().GetModel(Convert.ToInt32(strid));
            al.Add(md.Name);
            al.Add(md.Characteristic);
            al.Add(md.Method);
            return al;
        }

        //获取可添加菜列表
        [WebMethod]
        public static ArrayList GetDishByTypeid(string libraryID, string DishTypeid, string DishName, string StrStartIndex, string StrMaxSize)
        {
            ArrayList al = new ArrayList();
            StringBuilder strnotid = new StringBuilder();
            int startindex, maxsize, endindex = 0;
            bool isfinish = false;
            Int32.TryParse(StrStartIndex, out startindex);
            Int32.TryParse(StrMaxSize, out maxsize);

            DataTable dt_library_Dish = new Catering_Rules.library_Dish().GetList("libraryID=" + libraryID).Tables[0];
            if (dt_library_Dish != null && dt_library_Dish.Rows.Count > 0)
            {
                strnotid.Append("|");
                foreach (DataRow row in dt_library_Dish.Rows)
                {
                    strnotid.Append(row["DishID"].ToString() + "|");
                }
            }

            DataTable dt_DishType = new Catering_Rules.DishType().GetAllList(false).Tables[0];
            StringBuilder dishTypeArr = new StringBuilder();
            dishTypeArr.Append(DishTypeid + ",");
            GetDishTypeArr(dishTypeArr, DishTypeid, dt_DishType);
            DataTable DishList = new Catering_Rules.T_Dish().GetList("DTID in (" + dishTypeArr.ToString().TrimEnd(',') + ") and Name like '%" + DishName + "%'").Tables[0];
            DataTable dt_dish = new DataTable();
            dt_dish.Columns.Add("id");
            dt_dish.Columns.Add("DTID");
            dt_dish.Columns.Add("Name");
            for (int i = 0; i < DishList.Rows.Count; i++)
            {
                string strDishId ="|"+DishList.Rows[i]["id"].ToString()+"|";
                if (strnotid.ToString().IndexOf(strDishId) < 0)
                {
                    DataRow newrow = dt_dish.NewRow();
                    newrow["id"] = DishList.Rows[i]["id"];
                    newrow["DTID"] = DishList.Rows[i]["DTID"];
                    newrow["Name"] = DishList.Rows[i]["Name"];
                    dt_dish.Rows.Add(newrow);
                }
            }

            if (dt_dish != null && dt_dish.Rows.Count > 0)
            {
                al.Add(GetDishHtml(dt_dish, startindex, maxsize, out endindex, out isfinish));
            }
            else
            {
                al.Add("");
            }
            al.Add(endindex);
            al.Add(isfinish);
            al.Add("OK");

            return al;
        }

        /// <summary>
        /// 递归获取所有的菜谱子类ID
        /// </summary>
        /// <param name="dishtypearr">输出的类别集合</param>
        /// <param name="DishTypeID">类别ID</param>
        /// <param name="dt_dishtype">类别数据</param>
        public static void GetDishTypeArr(StringBuilder dishtypearr,string DishTypeID,DataTable dt_dishtype)
        {
            foreach (DataRow row in dt_dishtype.Select("ParentID=" + DishTypeID))
            {
                dishtypearr.Append(row["id"].ToString()+",");
                GetDishTypeArr(dishtypearr, row["id"].ToString(), dt_dishtype);
            }
        }


        public static string GetDishHtml(DataTable dt_Dish, int startindex, int maxsize, out int endindex, out bool isfinish)
        {
            StringBuilder sb = new StringBuilder();
            endindex = 0;
            int i = 1;
            sb.Append("{\"ObjInfo\":[");
            foreach (DataRow row in dt_Dish.Rows)
            {
                if (i < startindex)
                {
                    i++;
                    continue;
                }
                sb.Append("{\"index\":\"" + i.ToString() + "\",\"id\":\"" + row["id"].ToString() + "\",\"DTID\":\"" + row["DTID"].ToString() + "\",\"Name\":\"" + row["Name"].ToString() + "\"},");
                i++;
                if (i - startindex > maxsize) break;
            }
            endindex = i;
            isfinish = i >= dt_Dish.Rows.Count ? true : false;
            if (sb.ToString().Contains(','))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]}");
            return sb.ToString();
        }

        //选择菜
        protected void Tv_Dish_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (this.Tv_Dish.SelectedNode.Target != "item") //判断是否为菜品
                return;

            TreeNode tn = Tv_Dish.SelectedNode;
            string DishID = tn.Value.ToString();
            LoadInfo(DishID);
            GetDish(DishID);
            setLableValue(DishID);
        }

        private void GetDish(string str)
        {
            Catering_Rules.T_Dish crd = new Catering_Rules.T_Dish();

            Catering_Model.E_Dish cmd = crd.GetModel(Convert.ToInt32(str));
            this.Txt_caipin.Text = cmd.Name;
            this.txt_tedian.Text = cmd.Characteristic;
            this.Txt_zuofa.Text = cmd.Method;
            this.Txt_DTID.Text = cmd.DTID.ToString();
            this.Txt_FMID.Text = cmd.FMID.ToString();
            this.ImgCaipin.ImageUrl = cmd.Picture;

        }

        public void LoadInfo(string str)
        {
            Catering_Rules.T_Dish crd = new Catering_Rules.T_Dish();
            Catering_Model.E_Dish cmd = crd.GetModel(Convert.ToInt32(str));
            Catering_Rules.T_DishInfo crdi = new Catering_Rules.T_DishInfo();

            this.Rep_yuanliaoList.DataSource = crdi.GetList("DID=" + str).Tables[0];
            this.Rep_yuanliaoList.DataBind();

            setLableValue(str);
        }

        //菜谱库
        public void GetTableHtml()
        {
            System.Text.StringBuilder sb_Dish = new System.Text.StringBuilder();
            Catering.View_Operaction_Common voc = new View_Operaction_Common();
            DataTable dt = voc.TreeViewDataBind_Library();
            int i = 1;
            string strtest = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                sb_Dish.Append("<tr onclick=\"select_library(" + dr["id"].ToString() + ")\" style=\"cursor:pointer;\" >");
                sb_Dish.Append("    <td >" + i + "</td>");
                sb_Dish.Append("    <td id='RawName'>" + dr["LName"].ToString() + "</td>");
                sb_Dish.Append("    <td >&nbsp;</td>");
                sb_Dish.Append("    </tr>");

                i++;
            }
            Session["Library"] = sb_Dish.ToString();
        }

        private string GetElement(string strDishID, string strElement)
        {
            Catering_Rules.DishNutrien crdn = new Catering_Rules.DishNutrien();
            List<Catering_Model.DishNutrien> listnut = crdn.GetModelList("Dishid=" + strDishID + "   and element_name='" + strElement + "'");
            string strContent = string.Empty;
            if (listnut.Count > 0)
            {
                strContent = listnut[0].Content;
            }
            return strContent;
        }

        public void setLableValue(string strRawID)
        {
            this.lbl_reliang.Text = GetElement(strRawID, "能量");
            this.lbl_danbaizhi.Text = GetElement(strRawID, "蛋白质");
            this.lbl_zhifang.Text = GetElement(strRawID, "脂肪");
            this.lbl_tanshuihuahewu.Text = GetElement(strRawID, "碳水化合物");
            this.lbl_shanshixianwei.Text = GetElement(strRawID, "膳食纤维");
            this.lbl_weishengsuA.Text = GetElement(strRawID, "维生素A");
            this.lbl_weishengsuB1.Text = GetElement(strRawID, "维生素B1");
            this.lbl_weishengsuB2.Text = GetElement(strRawID, "维生素B2");
            this.lbl_weishengsuC.Text = GetElement(strRawID, "维生素C");
            this.lbl_weishengsuE.Text = GetElement(strRawID, "维生素E");
            this.lbl_shihuangchundangliang.Text = GetElement(strRawID, "视黄醇当量");
            this.lbl_nikesuan.Text = GetElement(strRawID, "尼克酸");
            this.lbl_huluobosu.Text = GetElement(strRawID, "胡萝卜素");
            this.lbl_gai.Text = GetElement(strRawID, "钙");
            this.lbl_ling.Text = GetElement(strRawID, "磷");
            this.lbl_jia.Text = GetElement(strRawID, "钾");
            this.lbl_na.Text = GetElement(strRawID, "钠");
            this.lbl_mei.Text = GetElement(strRawID, "镁");
            this.lbl_tie.Text = GetElement(strRawID, "铁");
            this.lbl_xin.Text = GetElement(strRawID, "锌");
            this.lbl_xi.Text = GetElement(strRawID, "硒");
            this.lbl_tong.Text = GetElement(strRawID, "铜");
            this.lbl_men.Text = GetElement(strRawID, "锰");
            this.lbl_dian.Text = GetElement(strRawID, "碘");

        }

        //获取虚列
        int i = 0;
        public string GetXuNiIndex()
        {
            i += 1;
            return i.ToString();
        }
    }
}